<template>
  <div class="page-container">
    <el-card class="box-card">
      <!-- 筛选表单 -->
      <el-form :inline="true" :model="filterForm" class="demo-form-inline">
        <el-form-item label="客服号:">
          <el-input clearable style="width: 120px" v-model="filterForm.customerService" placeholder="请输入客服号" />
        </el-form-item>
        <el-form-item label="代理状态:">
          <el-select clearable v-model="filterForm.agencyStatus" placeholder="请选择">
            <el-option label="打开代理" value="1" />
            <el-option label="关闭代理" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="代理机器人Id:">
          <el-input style="width: 150px" clearable v-model="filterForm.botId" placeholder="请输入代理机器人Id" />
        </el-form-item>
        <el-form-item label="代理机器人名称:">
          <el-input style="width: 170px" clearable v-model="filterForm.botUsername" placeholder="请输入代理机器人名称" />
        </el-form-item>
        <el-form-item label="代理钱包:">
          <el-input clearable style="width: 120px" v-model="filterForm.address" placeholder="请输入代理钱包" />
        </el-form-item>
        <el-form-item label="tg用户id:">
          <el-input style="width: 120px" clearable v-model="filterForm.tgUserId" placeholder="请输入tg用户id" />
        </el-form-item>
        <!-- <el-button type="primary" @click="onSearch">查询</el-button>
          <el-button @click="resetFilter">重置</el-button>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
          </el-button> -->
        <el-form-item>
          <el-button type="primary" @click="onSearch">查询</el-button>
          <el-button @click="resetFilter">重置</el-button>
          <el-button type="primary" @click="handleAdd">新建代理</el-button>
        </el-form-item>

        <!-- <div v-if="showMoreFilters">
         <el-form-item label="代理机器人Id:">
          <el-input clearable v-model="filterForm.botId" placeholder="请输入代理机器人Id" />
        </el-form-item>
        <el-form-item label="代理机器人名称:">
          <el-input clearable v-model="filterForm.botUsername" placeholder="请输入代理机器人名称" />
        </el-form-item>
        <el-form-item label="代理钱包:">
          <el-input clearable v-model="filterForm.address" placeholder="请输入代理钱包" />
        </el-form-item>
        <el-form-item label="tg用户id:">
          <el-input clearable v-model="filterForm.tgUserId" placeholder="请输入tg用户id" />
        </el-form-item>
        
          </div>

        <el-form-item>
           <el-button @click="toggleMoreFilters">
            {{ showMoreFilters ? '收起查询条件' : '更多查询条件' }}
          </el-button>

          <el-button type="primary" @click="onSearch">查询</el-button>
          <el-button @click="resetFilter">重置</el-button>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
          </el-button>
        </el-form-item> -->
      </el-form>

      <!-- 操作按钮 -->
      <!-- <div class="operation-buttons">
        <el-button type="primary" @click="handleAdd"
          ><el-icon><Plus /></el-icon
        ></el-button>
      </div> -->

      <!-- 表格 -->
      <div class="content-container">
        <!-- <AgentFilterMenu v-if="!isMobile" :active-agent-id="filterForm.agencyId" @select-agent="handleAgentSelect"
          class="agent-menu-container" /> -->

        <div class="table-container">
          <el-table :class="{ 'mobile-tablze-container': isMobile }" v-loading="loading" :data="tableData" border
            style="width: 100%; overflow-y: auto" @selection-change="handleSelectionChange">
            <!-- <el-table-column prop="id" label="id" /> -->
            <el-table-column prop="botId" label="ID" :width="isMobile ? 105 : null" />
            <el-table-column prop="tgUserId" label="tg用户id" :width="isMobile ? 105 : null" />
            <el-table-column :width="isMobile ? botUsernameWidth : null" prop="botUsername" label="代理机器人名称" />
            <!-- <el-table-column :width="botPathWidth" prop="botPath" label="代理机器人路由" /> -->
            <el-table-column prop="address" :width="isMobile ? addressWidth : null" label="代理钱包">
              <template #default="scope">
                <CopyableAddress :value="scope.row.address" :maxLength="16" />
              </template> </el-table-column>z
            <el-table-column prop="customerService" label="客服号" />

            <!-- <el-table-column prop="configJson" label="配置信息"  /> -->
            <el-table-column prop="balance" label="账户余额">
              <template #default="scope">
                {{ formatBalance(scope.row.balance) }}
              </template>
            </el-table-column>

            <!-- <el-table-column prop="groupId" label="群聊id">
          <template #default="scope">
            <p v-if="!scope.row.groupId == ''">
              {{ scope.row.groupId }}
            </p>
            <p v-else>暂无</p>
          </template>
        </el-table-column> -->
            <el-table-column prop="agencyStatus" :width="isMobile ? botIdWidth : null" label="代理状态">
              <template #default="scope">
                <el-tag :type="scope.row.agencyStatus === 1 ? 'success' : 'danger'">
                  {{ scope.row.agencyStatus === 1 ? "打开代理" : "关闭代理" }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" :width="isMobile ? 155 : null" />
            <el-table-column label="操作" width="90" fixed="right">
              <template #default="scope">
                <el-button type="primary" @click="handleEdit(scope.row)">编辑</el-button>
                <!-- <el-button type="danger" @click="handleDelete(scope.row)"
              >删除</el-button
            > -->
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <el-pagination class="pagination" :class="{ 'mobile-pagination': isMobile }"
            :current-page="pagination.currentPage" :page-sizes="[10, 20, 30, 50]" :page-size="pagination.pageSize"
            :layout="paginationLayout" :total="pagination.total" @size-change="handleSizeChange"
            @current-change="handleCurrentChange">
            <!-- <template v-if="isMobile" #default>
      <div class="mobile-pagination-info">
        第 {{ pagination.currentPage }}/{{ Math.ceil(pagination.total / pagination.pageSize) }} 页
      </div>
    </template> -->
          </el-pagination>
        </div>
      </div>
      <el-dialog v-model="dialogVisible" :title="dialogTitle" :width="dialogWidth" @close="resetForm">
        <el-form ref="editFormRef" :model="editForm" :label-width="labelWidth" :label-position="labelPosition">
          <!-- :rules="formRules"<el-form-item label="佣金比例 (%)" prop="brokerageRate">
            <el-input-number
              v-model="editForm.brokerageRate"
              :min="0"
              :max="100"
              :precision="2"
              controls-position="right"
            />
          </el-form-item> -->

          <!-- <el-form-item label="提现地址" prop="withdrawAddress">
            <el-input v-model="editForm.withdrawAddress" placeholder="请输入提现地址" />
          </el-form-item> -->

          <el-form-item label="服务商能量底价 (SUN)">
            <!-- <el-input
              v-model="editForm.serviceEnergyUnit"
              :min="0"
              :step="100000"
              controls-position="right"
            /> -->
            <el-input v-model="editForm.serviceEnergyUnit" type="number" :min="0" placeholder="请输入">
              <template #suffix>
                <span class="unit-text">TRX</span>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="服务商带宽底价 (SUN)">
            <el-input v-model="editForm.serviceNetUnit" type="number" :min="0" placeholder="请输入">
              <template #suffix>
                <span class="unit-text">TRX</span>
              </template>
            </el-input>
          </el-form-item>
          <!-- <el-form-item label="服务商带宽底价 (SUN)">
            <el-input
              v-model="editForm.serviceNetUnit"
              :min="0"
              :step="100000"
              controls-position="right"
            />
          </el-form-item> -->

          <el-form-item label="用户能量底价 (SUN)">
            <!-- <el-input
              v-model="editForm.userEnergyUnit"
              :min="0"
              :step="100000"
              controls-position="right"
            /> -->
            <el-input v-model="editForm.userEnergyUnit" type="number" :min="0" placeholder="请输入">
              <template #suffix>
                <span class="unit-text">TRX</span>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="用户带宽底价 (SUN)">
            <!-- <el-input
              v-model="editForm.userNetUnit"
              :min="0"
              :step="100000"
              controls-position="right"
            /> -->
            <el-input v-model="editForm.userNetUnit" type="number" :min="0" placeholder="请输入">
              <template #suffix>
                <span class="unit-text">TRX</span>
              </template>
            </el-input>
          </el-form-item>

          <el-divider>套餐价格设置</el-divider>

          <el-table :data="editForm.packagePriceList" border :class="{ 'mobile-dialog': isMobile }">
            <el-table-column label="套餐名称" prop="name">
              <!-- <template #default="{ row}">
                <el-input v-model="row.name" placeholder="套餐名称" />
              </template> -->
            </el-table-column>

            <el-table-column label="数量 (笔)" prop="count">
              <!-- <template #default="{ row, $index }">
                <el-input
                  v-model="row.count"
                  type="number"
                  :min="1"
                  controls-position="right"
                  @change="calculateTotalPrice($index)"
                />
              </template> -->
            </el-table-column>

            <el-table-column label="单价 (TRX)" prop="unitPrice" :width="isMobile ? '100' : null">
              <template #default="{ row, $index }">
                <el-input v-model="row.unitPrice" :min="0.1" type="number" controls-position="right"
                  @change="calculateTotalPrice($index)" :class="{ 'invalid-price': isInvalidPrice($index) }" />
                <div v-if="isInvalidPrice($index)" class="error-message">
                  单价不能低于服务商能量底价 ({{ editForm.serviceEnergyUnit }}
                  TRX)
                </div>
              </template>
            </el-table-column>

            <el-table-column label="总价 (TRX)" prop="totalPrice" :width="isMobile ? '100' : null">
              <template #default="{ row }">
                {{ row.totalPrice.toFixed(0) }}
              </template>
            </el-table-column>

            <!-- <el-table-column label="操作" width="80">
              <template #default="{ $index }">
                <el-button
                  type="danger"
                  icon="Delete"
                  circle
                  @click="removePackage($index)"
                />
              </template>
            </el-table-column> -->
          </el-table>

          <!-- <div style="margin-top: 10px; text-align: center">
            <el-button type="primary" @click="addPackage">添加套餐</el-button>
          </div> -->
        </el-form>

        <template #footer>
          <span class="dialog-footer-buttons">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitEdit">保存</el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
    <el-dialog v-model="addDialogVisible" title="新增代理" :width="dialogWidth" @close="resetAddForm">
      <el-form ref="addFormRef" :model="addForm" :rules="addFormRules" :label-position="labelPosition"
        :label-width="labelWidth">
        <el-form-item label="机器人Token" prop="botToken">
          <el-input v-model="addForm.botToken" placeholder="请输入机器人Token" clearable />
        </el-form-item>

        <el-form-item label="客服号" prop="customerService">
          <el-input v-model="addForm.customerService" placeholder="请输入客服号" clearable />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer-buttons">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAdd">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, computed, watch } from "vue";
import api from "../../network/api";
import { ElMessage } from "element-plus";
import { useWindowSize } from "@vueuse/core";
import AgentFilterMenu from "../../components/AgentFilterMenu.vue";
import CopyableAddress from "../../components/CopyableAddress.vue";

export default {
  name: "ProxyList",

  components: {
    CopyableAddress,
    AgentFilterMenu
  },
  setup() {
    const filterForm = ref({
      customerService: '',
      agencyStatus: '',
      botId: '',
      botUsername: '',
      address: '',
      tgUserId: '',
    });

    const addDialogVisible = ref(false);
    const addFormRef = ref(null);
    const addForm = ref({
      botToken: "",
      customerService: "",
      configJson: "",
    });

    const tableData = ref([]);
    const loading = ref(false);
    const multipleSelection = ref([]);
    const dialogVisible = ref(false);
    const dialogTitle = ref("编辑代理配置");
    const currentBotId = ref(0);
    const editFormRef = ref(null);
    const showMoreFilters = ref(false);

    const pagination = ref({
      currentPage: 1,
      pageSize: 10,
      total: 0,
    });

    const lastFetchParams = ref(null);

    const handleAgentSelect = (agentId) => {
      filterForm.value.agencyId = agentId;
      onSearch();
    };
    const editForm = ref({
      brokerageRate: 0,
      withdrawAddress: "",
      serviceEnergyUnit: 0,
      serviceNetUnit: 0,
      userEnergyUnit: 0,
      userNetUnit: 0,
      packagePriceList: [{ name: "", count: 0, unitPrice: 0, totalPrice: 0 }],
    });
    const addFormRules = {
      botToken: [
        { required: true, message: "请输入机器人Token", trigger: "blur" },
        // {
        //   type: "number",
        //   min: 0,
        //   max: 100,
        //   message: "佣金比例必须在0-100之间",
        //   trigger: "blur",
        // },
      ],
      customerService: [
        { required: true, message: "请输入客服号", trigger: "blur" },
      ],
    };

    const botIdWidth = ref(0);
    const botUsernameWidth = ref(0);
    const botPathWidth = ref(0);
    const addressWidth = ref(0);

    const calculateColumnWidths = () => {
      const measureElement = document.createElement("span");
      measureElement.style.position = "absolute";
      measureElement.style.visibility = "hidden";
      measureElement.style.whiteSpace = "nowrap";
      document.body.appendChild(measureElement);

      const getTextWidth = (text) => {
        measureElement.textContent = text;
        return measureElement.offsetWidth;
      };

      let maxBotIdWidth = 0;
      let maxBotUsernameWidth = 0;
      let maxBotPathWidth = 0;
      let maxaddressWidth = 0;

      // 计算表头宽度
      maxBotIdWidth = Math.max(maxBotIdWidth, getTextWidth("变动类型"));
      maxBotUsernameWidth = Math.max(
        maxBotUsernameWidth,
        getTextWidth("代理机器人名称")
      );
      maxBotPathWidth = Math.max(
        maxBotPathWidth,
        getTextWidth("代理机器人路由")
      );
      maxaddressWidth = Math.max(maxaddressWidth, getTextWidth("代理钱包"));

      // 计算表格数据宽度
      tableData.value.forEach((row) => {
        maxBotIdWidth = Math.max(maxBotIdWidth, getTextWidth(row.agencyStatus));
        maxBotUsernameWidth = Math.max(
          maxBotUsernameWidth,
          getTextWidth(row.botUsername)
        );
        maxBotPathWidth = Math.max(maxBotPathWidth, getTextWidth(row.botPath));
        maxaddressWidth = Math.max(maxaddressWidth, getTextWidth(row.address));
      });

      // 适当增加一些间距
      botIdWidth.value = maxBotIdWidth + 30;
      botUsernameWidth.value = maxBotUsernameWidth + 7;
      botPathWidth.value = maxBotPathWidth + 20;
      addressWidth.value = maxaddressWidth - 120;

      document.body.removeChild(measureElement);
    };

    watch(
      tableData,
      () => {
        calculateColumnWidths();
      },
      { immediate: true }
    );

    const { width: windowWidth } = useWindowSize();
    const dialogWidth = computed(() => {
      return windowWidth.value < 768 ? "90%" : "50%";
    });
    const labelPosition = computed(() => {
      return windowWidth.value < 768 ? "top" : "right";
    });
    const isMobile = computed(() => windowWidth.value < 768);
    // 计算标签宽度
    const labelWidth = computed(() => {
      return windowWidth.value < 768 ? "auto" : "120px";
    });

    const addPackage = () => {
      editForm.value.packagePriceList.push({
        name: `套餐${editForm.value.packagePriceList.length + 1}`,
        count: 10,
        unitPrice: 1.0,
        totalPrice: 10.0,
      });
    };
    const removePackage = (index) => {
      if (editForm.value.packagePriceList.length > 1) {
        editForm.value.packagePriceList.splice(index, 1);
      } else {
        ElMessage.warning("至少保留一个套餐");
      }
    };
    const paginationLayout = computed(() => {
      if (windowWidth.value < 768) {
        return 'sizes, prev, pager, next';
      } else {
        return 'total,sizes, prev, pager, next, jumper';
      }
    });
    // 计算套餐总价
    const calculateTotalPrice = (index) => {
      const pkg = editForm.value.packagePriceList[index];
      pkg.totalPrice = pkg.count * pkg.unitPrice;
    };
    // 重置表单
    const resetForm = () => {
      if (editFormRef.value) {
        editFormRef.value.resetFields();
      }
    };
    const handleEdit = (row) => {
      currentBotId.value = row.id;
      // console.log('row.id',row.id);

      try {
        // 解析配置信息
        const config = JSON.parse(row.configJson || "{}");
        // 初始化表单数据
        editForm.value = {
          brokerageRate: config.brokerageRate || 0,
          withdrawAddress: config.withdrawAddress || "",
          serviceEnergyUnit: Number(config.serviceEnergyUnit / 1e6) || 0,
          serviceNetUnit: Number(config.serviceNetUnit / 1e6) || 0,
          userEnergyUnit: Number(config.userEnergyUnit / 1e6) || 0,
          userNetUnit: Number(config.userNetUnit / 1e6) || 0,
          packagePriceList: config.packagePriceList?.map((pkg) => ({
            name: pkg.name || "",
            count: pkg.count || 0,
            unitPrice: pkg.unitPrice || 0,
            totalPrice: pkg.totalPrice || 0,
          })) || [{ name: "", count: 0, unitPrice: 0, totalPrice: 0 }],
        };
        dialogTitle.value = `编辑代理配置 - ${row.botUsername}`;
        dialogVisible.value = true;
      } catch (error) {
        console.error("解析配置信息失败:", error);
        ElMessage.error("配置信息格式错误");
      }
    };
    const submitEdit = () => {
      if (!validateAllPrices()) {
        return;
      }
      editFormRef.value.validate((valid) => {
        if (valid) {
          // 构建配置对象
          const config = {
            brokerageRate: editForm.value.brokerageRate,
            withdrawAddress: editForm.value.withdrawAddress,
            serviceEnergyUnit: Number(editForm.value.serviceEnergyUnit * 1e6),
            serviceNetUnit: Number(editForm.value.serviceNetUnit * 1e6),
            userEnergyUnit: Number(editForm.value.userEnergyUnit * 1e6),
            userNetUnit: Number(editForm.value.userNetUnit * 1e6),
            packagePriceList: editForm.value.packagePriceList.map((pkg) => ({
              name: pkg.name,
              count: pkg.count,
              unitPrice: pkg.unitPrice,
              totalPrice: pkg.totalPrice,
            })),
          };

          // 发送更新请求
          api
            .user_EditAgencySet(currentBotId.value, config)
            .then((res) => {
              if (res.data.code === 99999 && res.data.success) {
                ElMessage.success("配置更新成功");
                dialogVisible.value = false;
                fetchAgencyList(); // 刷新列表
              } else {
                ElMessage.error(res.data.msg || "更新失败");
              }
            })
            .catch((error) => {
              console.error("更新配置失败:", error);
              ElMessage.error("请求失败");
            });
        } else {
          ElMessage.warning("请填写完整信息");
        }
      });
    };
    const toggleMoreFilters = () => {
      showMoreFilters.value = !showMoreFilters.value;
    };

    // 格式化余额显示
    const formatBalance = (balance) => {
      // 检查是否为空值（null、undefined或空字符串）
      if (balance == null || balance === '') {
        return 0;
      }

      return Number(balance / 1e6).toLocaleString('zh-CN', {
        maximumFractionDigits: 10
      });
    };

    // 获取代理列表
    const fetchAgencyList = () => {

      const params = {
        pageNum: pagination.value.currentPage,
        pageSize: pagination.value.pageSize,
        ...filterForm.value,
      };
      const isSameAsLast = JSON.stringify(params) === JSON.stringify(lastFetchParams.value);

      if (isSameAsLast) {
        // console.log("参数未变化，跳过请求");
        return;
      }
      loading.value = true;
      api
        .user_agencyList(params)
        .then((res) => {
          // console.log("接口返回数据:", res.data);
          if (res.data.code === 99999 && res.data.success) {
            // 关键修复：使用 res.data.data.list 而不是 res.data.list
            tableData.value = res.data.data.list;
            pagination.value.total = res.data.data.total;
            lastFetchParams.value = params;
          } else {
            // ElMessage.error(res.msg || "获取代理列表失败");
          }
        })
        .catch((error) => {
          console.error("获取代理列表出错:", error);
          ElMessage.error("请求失败，请稍后重试");
        })
        .finally(() => {
          loading.value = false;
        });
    };

    // 搜索
    const onSearch = () => {
      const hasChanges = Object.keys(filterForm.value).some(key =>
        filterForm.value[key] !== (lastFetchParams.value?.[key] ?? null)
      );

      if (!hasChanges && pagination.value.currentPage === 1) {
        // ElMessage.info("搜索条件未变化");
        return;
      }

      pagination.value.currentPage = 1;
      fetchAgencyList();
    };

    // 重置筛选
    const resetFilter = () => {
      const isAlreadyReset = Object.values(filterForm.value).every(val => val === null);

      if (isAlreadyReset) {
        // ElMessage.info("已处于重置状态");
        return;
      }
      filterForm.value = {
        customerService: '',
        agencyStatus: '',
        botId: '',
        botUsername: '',
        address: '',
        tgUserId: '',
      };
      onSearch();
    };

    // 表格选择
    const handleSelectionChange = (val) => {
      multipleSelection.value = val;
    };

    // 分页大小变化
    const handleSizeChange = (size) => {
      pagination.value.pageSize = size;
      fetchAgencyList();
    };

    // 当前页变化
    const handleCurrentChange = (page) => {
      console.log("当前页变化:", page);

      pagination.value.currentPage = page;
      fetchAgencyList();
    };

    // 新增用户
    const handleAdd = () => {
      addDialogVisible.value = true;
    };
    const resetAddForm = () => {
      if (addFormRef.value) {
        addFormRef.value.resetFields();
      }
      addForm.value = {
        botToken: "",
        customerService: "",
      };
    };
    const submitAdd = () => {
      // 简单的前端验证
      if (!addForm.value.botToken.trim()) {
        ElMessage.warning("请输入机器人Token");
        return;
      }

      if (!addForm.value.customerService.trim()) {
        ElMessage.warning("请输入客服号");
        return;
      }

      // 发送新增请求
      api
        .new_robot(addForm.value)
        .then((res) => {
          if (res.data.code === 99999 && res.data.success) {
            ElMessage.success("新增代理成功");
            addDialogVisible.value = false;
            fetchAgencyList(); // 刷新列表
          } else {
            ElMessage.error(res.data.msg || "新增失败");
          }
        })
        .catch((error) => {
          console.error("新增代理失败:", error);
          ElMessage.error("请求失败");
        });
    };
    // 编辑用户
    // const handleEdit = (row) => {
    //   ElMessage.info(`编辑代理: ${row.botUsername}`);
    // };

    onMounted(() => {
      fetchAgencyList();
    });

    const validateUnitPrice = (index) => {
      const pkg = editForm.value.packagePriceList[index];
      const minPrice = parseFloat(editForm.value.serviceEnergyUnit);

      // 计算总价
      calculateTotalPrice(index);

      // 如果单价低于底价，显示错误信息
      if (pkg.unitPrice < minPrice) {
        ElMessage.warning(`套餐单价不能低于服务商能量底价 (${minPrice} TRX)`);
      }
    };
    const isInvalidPrice = (index) => {
      const pkg = editForm.value.packagePriceList[index];
      const minPrice = parseFloat(editForm.value.serviceEnergyUnit);
      return pkg.unitPrice < minPrice;
    };
    const validateAllPrices = () => {
      const minPrice = parseFloat(editForm.value.serviceEnergyUnit);

      for (let i = 0; i < editForm.value.packagePriceList.length; i++) {
        const pkg = editForm.value.packagePriceList[i];

        if (pkg.unitPrice < minPrice) {
          ElMessage.error(
            `套餐"${pkg.name}"的单价不能低于服务商能量底价 (${minPrice} TRX)`
          );
          return false;
        }
      }

      return true;
    };

    return {
      resetForm,
      filterForm,
      tableData,
      loading,
      multipleSelection,
      pagination,
      onSearch,
      resetFilter,
      handleSelectionChange,
      handleSizeChange,
      handleCurrentChange,
      handleAdd,
      handleEdit,
      formatBalance,
      dialogVisible,
      dialogTitle,
      editForm,
      editFormRef,
      addFormRules,
      handleEdit,
      addPackage,
      removePackage,
      calculateTotalPrice,
      validateUnitPrice,
      isInvalidPrice,
      validateAllPrices,
      submitEdit,
      showMoreFilters,
      toggleMoreFilters,
      addDialogVisible,
      addForm,
      handleAdd,
      resetAddForm,
      submitAdd,
      dialogWidth,
      labelPosition,
      labelWidth,
      isMobile,
      botIdWidth,
      botUsernameWidth,
      botPathWidth,
      addressWidth,
      handleAgentSelect,
      paginationLayout
    };
  },
};
</script>
<style scoped lang="less">
.el-form-item {
  transition: all 2s ease;
}

// 调整表单行间距
.demo-form-inline {
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
  // gap: 12px;

  .el-form-item {
    margin-bottom: 25px;
  }


}

.unit-text {
  color: #606266;
  padding-right: 8px;
  font-size: 14px;
}

.el-input {
  width: 100%;
}

.error-message {
  color: red;
  font-size: 12px;
  margin-top: 5px;
}

/* 调整表单行间距 */
.demo-form-inline {
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
  // gap: 12px;

  .el-form-item {
    margin-bottom: 25px;
  }
}

.unit-text {
  color: #606266;
  padding-right: 8px;
  font-size: 14px;
}

.el-input {
  width: 100%;
}

.error-message {
  color: red;
  font-size: 12px;
  margin-top: 5px;
}

.el-divider {
  margin: 30px 0;
}

.box-card {
  width: 100%;
  height: 90vh;
  overflow-y: auto;
  display: flex;
  flex-direction: column;

  &::-webkit-scrollbar {
    width: 1px;
    background: transparent;
  }

  &::-webkit-scrollbar-thumb {
    background: rgba(248, 248, 250, 0.2);
    border-radius: 6px;
    transition: background 0.3s;
  }

  &::-webkit-scrollbar-track {
    background: transparent;
  }

  .demo-form-inline {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    flex: 1;
    margin-bottom: 0;
  }

  .operation-buttons {
    margin-bottom: 20px;
    // flex: 1;
    float: right;
    margin-right: 30px;
  }

  .content-container {
    display: flex;
    flex: 1;
    flex-direction: row;
    height: 72.5vh;
    // background: #fce9e9;

    .table-container {
      flex: 1;
      display: flex;
      flex-direction: column;
      // min-width: 0;
      // background: #000; // 设置背景颜色为黑色
      // height: 79.9vh;

      .el-table {
        flex: 1;
        // background: #000;
        // max-height: 79.3vh;
      }

      .pagination {
        margin-top: 15px;
        float: right !important;
        display: flex;
        justify-content: flex-end;
        width: 100%;
      }
    }
  }

  .agent-menu-container {
    width: 240px;
    margin-right: 16px;
    flex-shrink: 0;
    max-height: 79.9vh;
  }

  .table-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    min-width: 0;
    // background: #000;
    max-height: 79.9vh;

    .el-table {
      flex: 1;
      max-height: 80vh;
    }

    .pagination {
      margin-top: 15px;
      float: right !important;
      display: flex;
      justify-content: flex-end;
      width: 100%;
    }
  }
}

// 将分页显示在最下面
.pagination {
  margin-top: 20px;
  float: right;
}

// :deep(.el-table__header) .el-table__cell {
//   white-space: nowrap !important;
//   text-overflow:clip !important;
//   overflow: hidden !important;
// }

// /* 表头单元格内容 */
// :deep(.el-table__header-wrapper) th > .cell {
//   white-space: nowrap !important;
//   // text-overflow: ellipsis !important;
//   overflow: hidden !important;
//   display: inline-block;
//   width: 100%;
// }
@media (max-width: 768px) {

  /* 对话框样式调整 */
  .edit-dialog,
  .add-dialog {
    .el-dialog__body {
      // padding: 15px;
    }

    .el-form-item {
      margin-bottom: 15px;

      .el-form-item__label {
        padding-bottom: 5px;
        text-align: left;
        width: 100% !important;
      }
    }
  }

  /* 对话框底部按钮 */
  .dialog-footer-buttons {
    display: flex;
    flex-wrap: wrap;

    .el-button {
      flex: 1;
      // margin: 5px;
      min-width: 100px;
    }
  }

  /* 调整表单元素宽度 */
  .el-input,
  .el-select,
  .el-input-number {
    width: 100% !important;
  }

  /* 调整卡片内边距 */
  .box-card {
    // padding: 10px;
    // height: auto;
    min-height: 88vh;
    overflow-y: auto;
    overflow-x: auto;

    .demo-form-inline {
      .el-form-item {
        margin-right: 10px;
        margin-bottom: 15px;
      }
    }
  }

  .mobile-dialog {
    .el-table__header .el-table__cell {
      white-space: nowrap !important;
    }
  }

  /* 分页样式调整 */
  .pagination {
    float: none;
    display: flex;
    justify-content: center;
    flex-wrap: nowrap;
    margin-top: 15px;
    // width: 300px;
  }

  :deep(.el-table__header) .el-table__cell {
    white-space: nowrap !important;
    text-overflow: clip !important;
    overflow: visible !important;
  }

  :deep(.el-table__header-wrapper) th>.cell {
    white-space: nowrap !important;
    overflow: visible !important;
    text-overflow: clip !important;
    display: inline-block;
    width: auto;
  }

  :deep(.el-table__body) .el-table__cell {
    white-space: nowrap !important;
    text-overflow: clip !important;
    overflow: visible !important;
  }

  .mobile-pagination {
    :deep(.el-pagination) {
      display: flex !important;
      flex-wrap: nowrap !important;
      overflow-x: auto !important;
      padding: 5px 0 !important;
      min-height: 32px !important;
      font-size: 12px !important;

      .el-pagination__sizes {
        font-size: 12px !important;
        transform: scale(0.9) !important;
        transform-origin: left center !important;
        white-space: nowrap !important;
        margin-right: 5px !important;
      }

      .btn-prev,
      .btn-next {
        min-width: 24px !important;
        height: 24px !important;
        padding: 0 5px !important;
        margin: 0 2px !important;
      }

      .el-pager {
        li {
          min-width: 24px !important;
          height: 24px !important;
          line-height: 24px !important;
          font-size: 12px !important;
          padding: 0 3px !important;
          margin: 0 2px !important;
        }
      }

      .el-pagination__jump {
        margin-left: 5px !important;
        font-size: 12px !important;

        .el-pagination__editor {
          width: 40px !important;

          .el-input__inner {
            height: 24px !important;
            padding: 0 5px !important;
            font-size: 12px !important;
          }
        }
      }
    }

    .mobile-pagination-info {
      font-size: 12px !important;
      margin-top: 5px !important;
      text-align: center !important;
    }
  }

  /* 强制覆盖Element UI默认样式 */
  :deep(.el-pagination) {
    --el-pagination-button-width: 24px !important;
    --el-pagination-button-height: 24px !important;
    --el-pagination-font-size: 12px !important;
  }

  :deep(.el-pagination button, .el-pagination li) {
    min-width: 24px !important;
    height: 24px !important;
    line-height: 24px !important;
    font-size: 12px !important;
  }

  :deep(.el-pagination__editor) {
    height: 24px !important;

    .el-input__inner {
      height: 24px !important;
      font-size: 12px !important;
    }
  }
}
</style>
